package com.siyoumi.component.http;

import com.siyoumi.util.XStr;
import lombok.NonNull;

import java.net.URI;
import java.util.HashMap;

public class InputData
        extends HashMap<String, Object>
        implements InputDataInterface {
    static public InputData getIns() {
        return new InputData();
    }

    /**
     * a=1&b=2 转 inputData
     *
     * @param url
     */
    static public InputData parse(String url) {
        URI uri = URI.create(url);
        String query = uri.getQuery();
        if (XStr.isNullOrEmpty(query)) {
            return getIns();
        }

        InputData inputData = getIns();
        String[] queryArr = query.split("&");
        for (String q : queryArr) {
            String[] kv = q.split("=");
            inputData.put(kv[0], kv[1]);
        }
        return inputData;
    }

    static public InputData fromRequest() {
        return XHttpContext.InputAll();
    }

    @Override
    public String input(@NonNull String k, String def) {
        String v = (String) get(k);
        if (XStr.isNullOrEmpty(v)) {
            return def;
        }
        return v.trim();
    }

    public Boolean existsKey(String key) {
        return containsKey(key);
    }
}
